//
//  ManagerController.m
//  test
//
//  Created by LeeBruce on 16/5/23.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "ManagerController.h"
#import "RootViewController.h"
#import "TopBackView.h"
#import "Common.h"
#import "QiniuSDK.h"
#import <UIImageView+WebCache.h>
#import "LoginViewController.h"
#import "WKProgressHUD.h"
#import "ZHPickView.h"
#import <AssetsLibrary/AssetsLibrary.h>//相册权限
#import <AVFoundation/AVCaptureDevice.h>//相机权限
#import <AVFoundation/AVMediaFormat.h>


@interface ManagerController ()<UITextFieldDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIGestureRecognizerDelegate,ZHPickViewDelegate>

@property (nonatomic,strong) UIImageView *imagev;
@property (nonatomic,strong) ZHPickView *pickV;
@property (nonatomic,strong) UIScrollView *scrollView;
@property (nonatomic,strong) UITextField *nameTextField;
@property (nonatomic,strong) UITextField *emailTextField;
@property (nonatomic,strong) UITextField *genderTextField;
@property (nonatomic,strong) UIButton *dateButton;
@property (nonatomic,strong) NSMutableArray *textFieldArray;
@property (nonatomic,strong) UIView *dateView;
@property (nonatomic,strong) UIDatePicker *datePicker;
@property (nonatomic,copy) NSString *valueString;

@property (nonatomic) int currentTextFieldIndex;

@property (nonatomic,strong) NSMutableDictionary *dataDictionary;


@property (nonatomic,copy) NSString *token;
@property (nonatomic,copy) NSString *qiNiuKey;

@property (nonatomic,strong) UIImageView *imageV1;
@property (nonatomic,strong) UIImageView *imageV2;
@property (nonatomic,copy) NSString *sexString;
@property (nonatomic,strong) WKProgressHUD *hud;

@end

@implementation ManagerController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.qiNiuKey = @"";
    self.valueString = @"";
    self.textFieldArray = [NSMutableArray array];
    self.dataDictionary = [NSMutableDictionary dictionary];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;

    
    TopBackView *topBackView= [[TopBackView alloc]initViewWithFrame:CGRectMake(0, 0, screenWidth, 64) andTitle:@"账户管理"];
    
    [topBackView.rightButton setTitle:@"保存" forState:UIControlStateNormal];
    topBackView.rightButton.titleLabel.font = Font(14);
    [topBackView.rightButton setTitleColor:WhiteColor forState:UIControlStateNormal];
    
    [topBackView.rightButton addTarget:self action:@selector(confirmButton) forControlEvents:UIControlEventTouchUpInside];
    
    
    [topBackView.leftButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:topBackView];
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self initDataSource];
    [self initSubviews];
    
    self.hud = [WKProgressHUD showInView:self.view withText:@"" animated:YES];

}


#pragma mark 获取个人信息 赋值
-(void)initDataSource
{

    //个人信息接口
    
    [Common requestWithUrlString:user_info contentType:application_json finished:^(id responseObj) {
        
        [self.hud dismiss:YES];
        
        if ([responseObj[@"success"] boolValue]) {
            
            
            self.dataDictionary = responseObj[@"data"];
//            NSLog(@"%@",self.dataDictionary);
            //赋值
            [self getValueString];
        } else {
            
            [WKProgressHUD popMessage:responseObj[@"message"] inView:self.view duration:1.5 animated:YES];

        }

    } failed:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
        
        [self.hud dismiss:YES];

    }];
    
}


-(void)getValueString
{
    
    [self.hud dismiss:YES];
    
    if ([self.dataDictionary[@"pic"] isEqual:[NSNull null]]) {
        self.imagev.image = [UIImage imageNamed:@"personal_picture"];
    } else {
    //拼接图片url
    NSString *urlString = [NSString stringWithFormat:@"%@",self.dataDictionary[@"pic"]];
    
//        [self.imagev sd_setImageWithURL:[NSURL URLWithString:urlString]];
       [self.imagev sd_setImageWithURL:[NSURL URLWithString:urlString] placeholderImage:[UIImage imageNamed:@"personal_picture"]];

    
    }
    
    
    if ([self.dataDictionary[@"gender"] isEqual:[NSNull null]]) {
        
        self.imageV1.image = [UIImage imageNamed:@"sex_unselect"];
        self.imageV2.image = [UIImage imageNamed:@"sex_unselect"];
        _sexString = @"";

        
    } else {
       
        if ([self.dataDictionary[@"gender"] isEqualToString:@"M"]) {
            self.imageV2.image = [UIImage imageNamed:@"sex_unselect"];
            self.imageV1.image = [UIImage imageNamed:@"sex_select"];
            
            _sexString = @"男";
            
        } else if([self.dataDictionary[@"gender"] isEqualToString:@"F"]){
            self.imageV1.image = [UIImage imageNamed:@"sex_unselect"];
            self.imageV2.image = [UIImage imageNamed:@"sex_select"];
            _sexString = @"女";

        } else {
            _sexString = @"";
        }

    }
    
   
    if ([self.dataDictionary[@"email"] isEqual:[NSNull null]]) {
        
        self.emailTextField.text = @"";
    } else {
        self.emailTextField.text = [NSString stringWithFormat:@"%@",self.dataDictionary[@"email"]];

    }
    
    

    self.nameTextField.text = [NSString stringWithFormat:@"%@",self.dataDictionary[@"phone"]];

    
    
    
    NSString *birthday ;
    if ([self.dataDictionary[@"birthday"] isEqual:[NSNull null]]) {
        birthday = @"";
    } else {
        birthday = [NSString stringWithFormat:@"%@",self.dataDictionary[@"birthday"]];

    }
    

    [self.dateButton setTitle:birthday forState:UIControlStateNormal];
    [self.dateButton setTitleColor:fontGrayColor forState:UIControlStateNormal];

    
}

-(NSString *)backDateWithString:(NSString *)string
{
    NSDate *nd = [NSDate dateWithTimeIntervalSince1970:[string integerValue]/1000];
    
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd"];
    NSString *dateString = [dateFormat stringFromDate:nd];
    
    return dateString;
}


-(void)initSubviews
{
    
    self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, screenWidth, screenHeight)];
    [self.view addSubview:self.scrollView];
    
    
    // 头像试图
    
    UIView *pictureView = [self backViewWithFrame:CGRectMake(0, 0, screenWidth, 78) andString:@"头像" andWidth:0];
    
    self.imagev = [[UIImageView alloc]initWithFrame:CGRectMake(screenWidth - 9 - 10 - 14 - 50, 14, 50, 50)];
    self.imagev.layer.cornerRadius = 25;
    self.imagev.layer.masksToBounds = YES;
    [pictureView addSubview:self.imagev];
    
    [self.scrollView addSubview:pictureView];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapToGetPicture)];
    [pictureView addGestureRecognizer:tap];
    
    
    UIImageView *arrowImg = [[UIImageView alloc]initWithFrame:CGRectMake( screenWidth - 10 - 14, 32, 10, 14)];
    arrowImg.image = [UIImage imageNamed:@"personal_arrow"];
    [pictureView addSubview:arrowImg];

    
    // 用户名
    
    UIView *nameView = [self backViewWithFrame:CGRectMake(0, CGRectGetMaxY(pictureView.frame) + 10, screenWidth, cellHeight) andString:@"手机号"];
    [self.scrollView addSubview:nameView];
    self.scrollView.backgroundColor = GrayColor;
    
    self.nameTextField = [[UITextField alloc]initWithFrame:CGRectMake(screenWidth -  14 - 250, 5, 250, cellHeight)];
    self.nameTextField.delegate = self;
    self.nameTextField.font = Font(12);
    self.nameTextField.userInteractionEnabled = NO;
    self.nameTextField.textAlignment = NSTextAlignmentRight;
    [nameView addSubview:self.nameTextField];
    self.nameTextField.textColor = fontGrayColor;
    
    //邮箱
    
    UIView *emailView = [self backViewWithFrame:CGRectMake(0, CGRectGetMaxY(nameView.frame), screenWidth, cellHeight) andString:@"邮箱"];
    [self.scrollView addSubview:emailView];
    
    self.emailTextField = [[UITextField alloc]initWithFrame:CGRectMake(CGRectGetMinX(self.nameTextField.frame), 0, 250, cellHeight)];
    self.emailTextField.keyboardType = UIKeyboardTypeEmailAddress;
    self.emailTextField.delegate = self;
    self.emailTextField.font = Font(12);
    self.emailTextField.textAlignment = NSTextAlignmentRight;
    [emailView addSubview:self.emailTextField];
    self.emailTextField.textColor = fontGrayColor;
    
    //性别
    
    UIView *genderView = [self backViewWithFrame:CGRectMake(0, CGRectGetMaxY(emailView.frame), screenWidth, cellHeight) andString:@"性别"];
    [self.scrollView addSubview:genderView];
    
    UIButton *buttonF = [UIButton buttonWithType:UIButtonTypeCustom];
        buttonF.frame = CGRectMake(screenWidth - 40 - 15, 0, 40, cellHeight);
        [genderView addSubview:buttonF];
        [buttonF addTarget:self action:@selector(buttonF) forControlEvents:UIControlEventTouchUpInside];
    
    self.imageV2 = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"sex_unselect"]];
    self.imageV2.frame = CGRectMake(0, CGRectGetMidY(buttonF.frame) - 6.5, 13, 13);
    [buttonF addSubview:self.imageV2];
    
    UILabel *labelF = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(self.imageV2.frame) + 8, 0, 20, cellHeight)];
    labelF.text = @"女";
    labelF.textColor = fontGrayColor;
    labelF.font = Font(12);
    [buttonF addSubview:labelF];
    
    UIButton *buttonM = [UIButton buttonWithType:UIButtonTypeCustom];
    buttonM.frame = CGRectMake(screenWidth - 40 - 15 - 22 - 40, 0, 40, cellHeight);
    [genderView addSubview:buttonM];
    [buttonM addTarget:self action:@selector(buttonM) forControlEvents:UIControlEventTouchUpInside];
    
    self.imageV1 = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"sex_unselect"]];
    self.imageV1.frame = CGRectMake(0, CGRectGetMidY(buttonF.frame) - 6.5, 13, 13);
    [buttonM addSubview:self.imageV1];
    
    UILabel *labelM = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(self.imageV1.frame) + 8, 0, 20, cellHeight)];
    labelM.text = @"男";
    labelM.textColor = fontGrayColor;
    labelM.font = Font(12);
    [buttonM addSubview:labelM];
    
    
    
//    self.genderTextField = [[UITextField alloc]initWithFrame:CGRectMake(CGRectGetMinX(self.nameTextField.frame), 0, 150, cellHeight)];
//    self.genderTextField.delegate = self;
//    self.genderTextField.font = Font(12);
//    self.genderTextField.textAlignment = NSTextAlignmentRight;
////    [genderView addSubview:self.genderTextField];
//    self.genderTextField.textColor = fontGrayColor;
//    UIButton *sexButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    sexButton.frame = CGRectMake(0, 0, 150, cellHeight);
//    [self.genderTextField addSubview:sexButton];
//    [sexButton addTarget:self action:@selector(sexButton) forControlEvents:UIControlEventTouchUpInside];
    
    
    //出生日期
    UIView *dateView = [self backViewWithFrame:CGRectMake(0, CGRectGetMaxY(genderView.frame), screenWidth, cellHeight) andString:@"出生日期" andWidth:0];
    [self.scrollView addSubview:dateView];
    
    self.dateButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _dateButton.frame = CGRectMake(screenWidth - 268, 0, 250, cellHeight);
    _dateButton.layer.cornerRadius = 5;
    self.dateButton.titleLabel.font = Font(12);
    self.dateButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;

    [_dateButton addTarget:self action:@selector(dateButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [_dateButton setTintColor:fontGrayColor];
    
    
    [dateView addSubview:self.dateButton];
    
    
    self.textFieldArray = [NSMutableArray arrayWithObjects:self.nameTextField,self.emailTextField,self.genderTextField,nil];
    
//    
//
    UIButton *logoutButton = [UIButton buttonWithType:UIButtonTypeCustom];
    logoutButton.backgroundColor = WhiteColor;
    logoutButton.frame = CGRectMake(0, CGRectGetMaxY(dateView.frame) + 10, screenWidth - 0, cellHeight);
    [logoutButton setTitle:@"退出登录" forState:UIControlStateNormal];
//    logoutButton.layer.cornerRadius = 5;
    logoutButton.titleLabel.font = Font(13);
    [logoutButton addTarget:self action:@selector(logoutButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [logoutButton setTitleColor:littleBlackColor forState:UIControlStateNormal];
    
    
    [self.scrollView addSubview:logoutButton];
    
    
//    [self initToolBar];
    
}


-(void)initToolBar
{
    UIToolbar *toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0,screenWidth, 35 * kHeight)];
    //    [self.view addSubview:toolBar];
    
    UIBarButtonItem *btnPlace = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    
    UIBarButtonItem *lastButton = [[UIBarButtonItem alloc]initWithTitle:@"上一个" style:UIBarButtonItemStylePlain target:self action:@selector(lastOneFirstResponser:)];
    
    [lastButton setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:15 * kHeight], NSFontAttributeName,BlackColor,NSForegroundColorAttributeName,nil] forState:UIControlStateNormal];

    
    UIBarButtonItem *nextButton = [[UIBarButtonItem alloc]initWithTitle:@"下一个" style:UIBarButtonItemStylePlain target:self action:@selector(nextOneFirstResponder:)];
    
     [nextButton setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:15 * kHeight], NSFontAttributeName,BlackColor,NSForegroundColorAttributeName,nil] forState:UIControlStateNormal];
    
    UIBarButtonItem *doneButton = [[UIBarButtonItem alloc]initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(keyBoardExit:)];
    
     [doneButton setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:15 * kHeight], NSFontAttributeName,BlackColor,NSForegroundColorAttributeName,nil] forState:UIControlStateNormal];
    
    NSArray *itemsArray = @[lastButton,nextButton,btnPlace,doneButton];
    toolBar.items = itemsArray;
    
    self.nameTextField.inputAccessoryView = toolBar;
    self.emailTextField.inputAccessoryView = toolBar;
    self.genderTextField.inputAccessoryView = toolBar;
    
}

-(void)nextOneFirstResponder:(UIBarButtonItem *)sender
{
    if (_currentTextFieldIndex + 1 <= 1) {
        UITextField *textField = self.textFieldArray[_currentTextFieldIndex + 1];
        [textField becomeFirstResponder];
    }
}

-(void)lastOneFirstResponser:(UIBarButtonItem *)sender
{
    if (_currentTextFieldIndex - 1 >= 0) {
        UITextField *textField = self.textFieldArray[_currentTextFieldIndex - 1];
        [textField becomeFirstResponder];
    }
}

-(void)keyBoardExit:(UIBarButtonItem *)sender
{
    [self.view endEditing:YES];
}

#pragma mark UITextFieldDelegate

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    
    [self.dateView removeFromSuperview];
    [self.pickV removeFromSuperview];
    
    if (textField == self.nameTextField) {
        _currentTextFieldIndex = 0;
    }
    
    if (textField == self.emailTextField) {
        _currentTextFieldIndex = 1;
    }
    
    if (textField == self.genderTextField) {
        _currentTextFieldIndex = 2;
        [self sexButton];
    
    
    }
    
    
    
}

//性别

-(void)buttonF
{
    self.imageV2.image = [UIImage imageNamed:@"sex_select"];
    self.imageV1.image = [UIImage imageNamed:@"sex_unselect"];
    _sexString = @"女";
}

-(void)buttonM
{
    self.imageV1.image = [UIImage imageNamed:@"sex_select"];
    self.imageV2.image = [UIImage imageNamed:@"sex_unselect"];
    _sexString = @"男";

}



-(void)sexButton
{
    _currentTextFieldIndex = 2;

    [self.view endEditing:YES];
//    [self.dateView removeFromSuperview];
    [self.pickV removeFromSuperview];

    _pickV=[[ZHPickView alloc] initPickviewWithPlistName:@"一组数据" isHaveNavControler:NO];

   _pickV.delegate=self;

   [_pickV show];
}

//获取图片
-(void)tapToGetPicture
{
    [self photoButton];

}

//获取时间选择框
-(void)dateButtonAction
{
    [self.pickV removeFromSuperview];
    _currentTextFieldIndex = 3;

    
    [self.view endEditing:YES];
    
    
    NSDate *date=[NSDate date];
    _pickV=[[ZHPickView alloc] initDatePickWithDate:date datePickerMode:UIDatePickerModeDate isHaveNavControler:NO];
    _pickV.delegate=self;
    
    [_pickV show];

    
}

#pragma mark 退出登录
-(void)logoutButtonAction
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:nil forKey:@"login"];
    [userDefaults setObject:nil forKey:login_token];

//    LoginViewController *loginVC = [[LoginViewController alloc]init];
//    UINavigationController *loginNC = [[UINavigationController alloc]initWithRootViewController:loginVC];

    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self.navigationController popViewControllerAnimated:YES];
        
//        [self presentViewController:loginNC animated:YES completion:nil];
        
    });
    
}



-(void)addDate:(UIDatePicker *)picker
{
    NSString *string = [NSString stringWithFormat:@"%@", picker.date];
    NSArray *array = [string componentsSeparatedByString:@" "];
    _valueString = array[0];
}

-(void)cancleButtonAction
{
    [UIView animateWithDuration:0.2 animations:^{
        self.dateView.frame = CGRectMake(0,screenHeight ,screenWidth, 340 * kHeight);
        
        [self.dateView removeFromSuperview];
    }];
}

-(void)confirmButtonAction
{
    
    [self.dateButton setTitle:_valueString forState:UIControlStateNormal];
    [self.dateButton setTitleColor:fontGrayColor forState:UIControlStateNormal];
    //button 文字对左靠齐
    
    [UIView animateWithDuration:0.2 animations:^{
        self.dateView.frame = CGRectMake(0,screenHeight , screenWidth, 340 * kHeight);
        
        [self.dateView removeFromSuperview];
    }];
}


-(void)confirmButton
{
    [self changePersonInfo];

}
-(UIView *)backViewWithFrame:(CGRect)frame andString:(NSString *)string andWidth:(float)width
{
    UIView *view = [[UIView alloc]initWithFrame:frame];
    view.backgroundColor = WhiteColor;
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(18, frame.size.height/2 - 10, 100, 20)];
    label.text = string;
    label.font = Font(13);
    label.textColor = littleBlackColor;
    
    
    
    UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(width,frame.size.height - 0.5, screenWidth , 0.5)];
    label1.backgroundColor = LineGrayColor;
    
    [view addSubview:label1];
    
    //    [view addSubview:imageV];
    [view addSubview:label];
    [self.scrollView addSubview:view];
    
    
    //    dispatch_async(dispatch_get_global_queue(0, 0), ^{
    //        // 处理耗时操作的代码块...
    //
    //        //通知主线程刷新
    //        dispatch_async(dispatch_get_main_queue(), ^{
    //            //回调或者说是通知主线程刷新，
    //        });
    //
    //    });
    
    
    return  view;
    
}

-(UIView *)backViewWithFrame:(CGRect)frame andString:(NSString *)string
{
    UIView *view = [[UIView alloc]initWithFrame:frame];
    view.backgroundColor = WhiteColor;
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(18, frame.size.height/2 - 10, 100, 20)];
    label.text = string;
    label.font = Font(13);
    label.textColor = littleBlackColor;
    
    
    
    UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(18,frame.size.height - 0.5, screenWidth , 0.5)];
    label1.backgroundColor = LineGrayColor;
    
    [view addSubview:label1];
    
//    [view addSubview:imageV];
    [view addSubview:label];
    [self.scrollView addSubview:view];
    
    
//    dispatch_async(dispatch_get_global_queue(0, 0), ^{
//        // 处理耗时操作的代码块...
//        
//        //通知主线程刷新
//        dispatch_async(dispatch_get_main_queue(), ^{
//            //回调或者说是通知主线程刷新，
//        });
//        
//    });
    
    
    return  view;
    
}

#pragma mark UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{
        
        UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
        
        self.imagev.image = image;
        
        //上传服务器
        [self getTokenFromQN];
        
    }];
}

-(void)viewWillAppear:(BOOL)animated{
    
    self.navigationController.navigationBarHidden = YES;
    
    RootViewController *rootVC = [RootViewController defaultsTabBar];
    [rootVC setTabBarHidden:YES];
    
    NSNotificationCenter *notification = [NSNotificationCenter defaultCenter];
    [notification addObserver:self selector:@selector(popSelf) name:@"dismiss" object:nil];
    
}

-(void)popSelf
{
    [self .navigationController popViewControllerAnimated:NO];
}



-(NSData *)getImageWith:(UIImage *)image
{
    NSData *data = nil;
    if (UIImagePNGRepresentation(image)) {
        
        data = UIImageJPEGRepresentation(image, 1);
        
        
    } else {
        data = UIImagePNGRepresentation(image);
        
        
    }
    
    return data;
}


#pragma mark 拍照
-(void)getPictureFromCamera
{
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    
    [self presentViewController:picker animated:YES completion:nil];
}

#pragma mark 从相册选取
-(void)getPictureFromLibrary
{
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    [self presentViewController:picker animated:YES completion:nil];
    
}

#pragma mark 从七牛获取Token
-(void)getTokenFromQN
{
    
    [Common requestWithUrlString:qiniu_token contentType:application_json finished:^(id responseObj) {
        if ([responseObj[@"success"] boolValue]) {
            
            self.token = responseObj[@"data"];
            [self uploadImageToQNWithData:[self getImageWith:self.imagev.image]];
        }
    } failed:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];
    

}

-(void)uploadImageToQNWithData:(NSData *)data
{
    
    QNUploadManager *upManager = [[QNUploadManager alloc]init];
    
    QNUploadOption *uploadOption = [[QNUploadOption alloc]initWithMime:nil progressHandler:^(NSString *key, float percent) {
        
    } params:nil checkCrc:NO cancellationSignal:nil];
    
    [upManager putData:data key:nil token:self.token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        
        self.qiNiuKey = resp[@"key"];
        
        
    } option:uploadOption];
}

-(void)changePersonInfo
{
    NSDictionary *dictionay = [NSDictionary dictionary];
    
    if (self.nameTextField.text.length <= 0 ) {
        self.nameTextField.text = @"";
    }
    
    
    
    
    if (self.emailTextField.text.length <= 0 ) {
        self.emailTextField.text = @"";
    }
    
    
    NSString *genderString = [NSString string];
    if (_sexString >= 0) {
        
        if ([_sexString isEqualToString:@"男"]) {
            genderString = @"M";
        } else if ([_sexString isEqualToString:@"女"]) {
            genderString = @"F";
        }
    } else {
        
        if ([self.dataDictionary[@"gender"] isEqual:[NSNull null]]) {
            genderString = @"";

        } else {
            genderString = self.dataDictionary[@"gender"];


        }
    }
    
    
    if (self.valueString.length <= 0 ) {
        
        if (self.dateButton.titleLabel.text.length <= 0) {
            self.valueString = @"";
        } else {
        self.valueString = self.dateButton.titleLabel.text;
        }
    }
    
    
    if (self.qiNiuKey.length > 0) {
        
    } else {
        
        if ( [[NSString stringWithFormat:@"%@",self.dataDictionary[@"picKey"]] isEqual:[NSNull null]]) {
            self.qiNiuKey = @"";


        } else {
            
            self.qiNiuKey = self.dataDictionary[@"picKey"];

        }
    }
    
    
    
    dictionay = @{@"name":self.nameTextField.text,
                  @"email":self.emailTextField.text,
                  @"gender":genderString,
                  @"birthday":_valueString,
                  @"pic":self.qiNiuKey,
                  @"pwd":@" "
                  };
    
    
    Common *c = [[Common alloc]init];
    [c afPostRequestWithUrlString:user_modify parms:dictionay finishedBlock:^(id responseObj) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
                
        if ([dic[@"success"] boolValue]) {
            
                    [WKProgressHUD popMessage:dic[@"message"] inView:self.view duration:1.5 animated:YES];

            //延迟执行
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                
                [self backAction];
                
            });
            

        } else {
            [WKProgressHUD popMessage:dic[@"message"] inView:self.view duration:1.5 animated:YES];
        }
        
    } failedBlock:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];
    
}



-(void)photoButton
{
    __weak typeof(self) weakSelf = self;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        
        [weakSelf getPictureFromCamera];

    }];
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"从相册选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        [weakSelf getPictureFromLibrary];

    }];
    
    [alert addAction:action1];
    [alert addAction:action2];
    [alert addAction:action3];
    
    
    [self presentViewController:alert animated:YES completion:nil];
    
}


-(void)alertControllerWith:(NSString *)string andInteger:(NSInteger)integer
{
    
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示" message:string preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:nil];
    [alertC addAction:action];
    
    [self presentViewController:alertC animated:YES completion:nil];
    
    if (integer == 1) {
        //延迟执行
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [alertC dismissViewControllerAnimated:YES completion:nil];
            
            [self backAction];
            
        });
    }
    
    
}

-(void)backAction
{
    
    [self.pickV removeFromSuperview];
    [self.navigationController popViewControllerAnimated:YES];
 
}




-(void)textFieldDidEndEditing:(UITextField *)textField
{
    
    [UIView animateWithDuration:0.3 animations:^{
        
        self.scrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        
    } completion:^(BOOL finished) {
        
    }];
}





#pragma mark ZhpickVIewDelegate

-(void)toobarDonBtnHaveClick:(ZHPickView *)pickView resultString:(NSString *)resultString{
    
    if (_currentTextFieldIndex == 2) {
        
        self.genderTextField.text=resultString;

    } else {
        
        NSString *string = [NSString stringWithFormat:@"%@", resultString];
        NSArray *array = [string componentsSeparatedByString:@" "];
        _valueString = array[0];

        [self.dateButton setTitle:_valueString forState:UIControlStateNormal];
    }
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark UITextFieldDelegate
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([string isEqualToString:@"\n"]) {
        [textField resignFirstResponder];
        return NO;
    }
    return YES;
}



-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
